package com.lyb.ui.controller;

import com.lyb.Utils;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * 命令行页面的控制器
 *
 * @author Dayun Mr.Alpaca
 * @version 1.4.0
 */
public class CmdController implements Initializable {
    @FXML
    public TextField cmdInputLabel;
    @FXML
    public TextArea cmdOutputText;
    @FXML
    public TextField cmdSign;
    @FXML
    public TextField cmdInputText;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        cmdOutputText.setText("");
        cmdInputText.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.ENTER) {
                /* 回车时若系统允许命令输入则保存当前命令 */
                if (Utils.isCanInputFlag()) {
                    Utils.guiInput(cmdInputText.getText());
                    cmdInputText.setText("");
                }
                /* 刷新输出内容 */
                cmdOutputText.appendText(Utils.getCommandOutput());
                /* 移动光标到末尾 */
                cmdOutputText.positionCaret(cmdOutputText.getText().length());
            }
        });


        /* 定期检查当前系统是否需要输入文件内容 */
        KeyFrame fileFrame = new KeyFrame(Duration.millis(500), event -> {
            if (Utils.isCanFileFlag()) {
                fileInput();
                Utils.setCanFileFlag(false);
            }
        });

        /* 添加动画事件到时间线 */
        Timeline timeline = new Timeline();
        timeline.getKeyFrames().addAll(fileFrame);
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.setAutoReverse(true);
        timeline.play();
    }

    /**
     * 弹窗读取用户输入作为文件内容
     */
    private void fileInput() {
        try {
            Stage stage = new Stage();
            Parent root = FXMLLoader.load(CmdController.class.getResource("/view/input.fxml"));
            stage.setTitle("文件内容");
            Scene scene = new Scene(root);
            scene.getStylesheets().add("/css/UI.css");
            stage.setScene(scene);
            stage.setResizable(false);
            stage.show();
        } catch (IOException e) {
            System.out.println("[系统]: 系统出现异常");
            System.exit(303);
        }
    }
}
